import { getToken, setToken, getInfo, clear, setInfo } from '@/utils/auth'
import { resetRouter } from '@/router'
import { login } from '@/api/login/login'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}
const state = getDefaultState()
// mutations 改变store中的值,参数为state
const mutations = {
  // 重置 token 被空的覆盖
  RESET_STATE: (state) => {
    // Object.assgin拷贝对象,后面的相同属性覆盖前面的
    Object.assign(state, getDefaultState())
  },
  // 在vuex中存储token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 存储名字
  SET_NAME: (state, info) => {
    state.name = info.nickname
  },
  // 存储头像
  SET_AVATAR: (state, info) => {
    state.avatar = info.icon
  }
}

// 异步修改state
const actions = {
  // user login
  // 利用vuex中数据的修改来
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      login(data).then(response => {
        commit('SET_TOKEN', response.data.token)
        setToken(response.data.token)
        setInfo(response.data.userInfo)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  getInfo({ commit }) {
    const info = getInfo()
    commit('SET_NAME', JSON.parse(info))
    commit('SET_AVATAR', JSON.parse(info))
  },
  // 退出登录
  logout({ commit, state }) {
    return new Promise(() => {
      // 清除本地数据
      clear()
      // 重置路由
      resetRouter()
      commit('RESET_STATE')
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

